package tr.edu.yildiz.ce.app_manager.dao.impl.hibernate;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import tr.edu.yildiz.ce.app_manager.dao.BasicDao;
import tr.edu.yildiz.ce.app_manager.model.BasicObject;
@Transactional
public class BasicDaoImpl<T extends BasicObject,ID> implements
		BasicDao<T,ID> {

	private Class<T> persistentClass;

	@PersistenceContext
	private EntityManager entityManager;

	protected EntityManager getEntityManager() {
		return this.entityManager;
	}

	public BasicDaoImpl() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	public T findById(ID id) {
		T instance = entityManager.find(getPersistentClass(), id);
		return instance;
	}
	
	@Override
	public List<T> listAll() {
		Query query = entityManager.createQuery("FROM "
				+ getPersistentClass().getName());
		return query.getResultList();
	}

	@Override
	public void persist(T t) {
		if (t.isUpdateMode()){
			entityManager.merge(t);
		}else {
			entityManager.persist(t);
		}
	}

	@Override
	public void merge(T t) {
		entityManager.merge(t);
	}
	
	@Override
	public T get(ID id) {
		return entityManager.find(persistentClass, id);
	}

	@Override
	public void remove(T t) {
		T o = entityManager.merge(t);
		entityManager.remove(o);
		
	}

}
